/**
 * Copyright (c) 2010
 * Bert Young. UESTC. 
 */

#ifndef BERT_MEMORYPOOL_H
#define BERT_MEMORYPOOL_H

#include <new>

class MemoryPool
{
private:
	/**
	 * The min size that pool can deal
	 */
	static const int MIN_SIZE = sizeof( void * );
	/**
	 * The max size that pool can deal
	 */
	static const int MAX_SIZE = 1024; // 1KB
	/**
	 * Pool buckets
	 */
	static const unsigned BUCKETS = MAX_SIZE - MIN_SIZE + 1;
	/**
	 * Bunch
	 */
	static const unsigned TRUNK_NUM = 16;
	/**
	 * The maximum total size of pool
	 */
	static const unsigned MAXSIZE_MEMORY = 16 * 1024 * 1024;  //  16MB
	/**
	 * The memory node definition
	 */
	struct mem_node
	{
		struct mem_node * next_free;
	};
	/**
	 * Free memory list
	 */
	static __thread mem_node * free_list[BUCKETS];
	/**
	 * The pool size available
	 */
	static __thread unsigned available_bytes;
	/**
	 * Find the bucket fits size
	 */
	static unsigned getIndex(unsigned  size );
protected:
	/**
	 * Constructor
	 */
	MemoryPool();
public:
	/**
	 * Allocate #size bytes
	 */
	static void * allocate(unsigned size);
	/**
	 * Free p
	 */
	static void deallocate(void * p, unsigned size );
	/**
	 * Placement new
	 */
	static void * operator new(unsigned size, void *p);
	/**
	 * Operator new
	 */
	static void * operator new(unsigned size);
	/**
	 * Operator delete
	 */
	static void operator delete( void * p , unsigned size);
};

#endif

